import router from '@/router'
import store from '@/store'
const whiteList = ['/login', '/404']

import NProgress from 'nprogress' // 引入一份进度条插件
import 'nprogress/nprogress.css' // 引入进度条样式

router.beforeEach(async(to, form, next) => {
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.userId) {
        const { roles: { menus }} = await store.dispatch('user/getUserInfo')
        // console.log(menus)
        const result = await store.dispatch('permission/filterRoutes', menus)
        // console.log(result)
        router.addRoutes([...result, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})
router.afterEach(() => NProgress.done)
